// JavaScript Document

var system = {
    /**
     * The page to use for all AJAX processing on the server
     */
    ajax_page: 'ajax_pages/system.php',
    /**
     * System Page List Cache. This will be used to store a data for the list of
     * pages to link to once the a Site Linker has been used. This will improve
     * performance since the processing will done only once on the server side
     */
    page_list_cache: null,
    /**
     * Initialises the system helpers
     **/
    init: function() {

        // configure the global ajax experience
        $p.ajaxConfig({
            onStart: function() {
                $p('#ajax-progress').css('visibility', 'visible');
            },
            onComplete: function() {
                $p('#ajax-progress').css('visibility', 'hidden');
            }
        });

        system.createPopup();
        system.createPageLinkers();
        system.createHelpIcons();
    },
    /**
     * Helper method for retrieving the scroll offsets for the current window
     **/
    getScrollXY: function() {
        var scrOfX = 0, scrOfY = 0;
        if (typeof(window.pageYOffset) == 'number') {
            //Netscape compliant
            scrOfY = window.pageYOffset;
            scrOfX = window.pageXOffset;
        } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
            //DOM compliant
            scrOfY = document.body.scrollTop;
            scrOfX = document.body.scrollLeft;
        } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
            //IE6 standards compliant mode
            scrOfY = document.documentElement.scrollTop;
            scrOfX = document.documentElement.scrollLeft;
        }
        return [scrOfX, scrOfY];
    },
    /**
     * Create the Help Information popup component
     *
     * @since 1.0
     **/
    createPopup: function() {
        var popup = document.createElement("div");
        popup.style.position = "absolute";
        popup.style.top = "0px";
        popup.style.left = "0px";
        popup.style.zIndex = "1500";

        popup.innerHTML = '<div id=\'help-dialog\' class="small user_type_info" id="type_info" '
                + 'style="position: absolute; width: 350px; top: 0px; left: 0px; height: 200px; background-color: #fffff9; border: solid #ccc 1px; overflow: hidden; display: none; z-index: 2000;">'
                + '    <div style="text-align:right; padding: 4px; border-bottom: solid #ccc 1px;">'
                + '       <a href="#" onclick="system.hidePopup(); return false;">Close</a> '
                + '    </div>'
                + '    <div id=\'popup-content\' style=\'line-height: 18px; overflow: auto;\'></div>'
                + '</div>';

        $("body").append(popup);
    },
    /**
     * Hides the Help Dialog if visible. This method was introduced to the help
     * solve a problem where the Help Dialog cannot appear above applets. The code
     * makes all applets visibile after the dialog is closed.
     */
    hidePopup: function() {
        $p('#help-dialog').hide(function() {
            // hide any applets on the page
            var applets = $p.all("applet");
            for (var i = 0; i < applets.length; i++) {
                applets[i].style.visibility = 'visible';
            }
        });
    },
    /**
     * Create the Help Icons for the various fields
     *
     * @since 1.0
     */
    createHelpIcons: function() {
        var query = "action=load_field_helps";

        $p.post(system.ajax_page, query, function(result) {
            var id_array = null;

            // if this browser is modern enough and supports JSON natively, use it
            if (JSON) {
                try {
                    id_array = JSON.parse(result); // parse result passed from ajax request
                } catch (e) {
                    //$p.inform("Failed To Parse Response From Server As JSON in system.js");
                    return;
                }


            } else {
                // use the unsafe eval method in older browsers
                // it is their fault if they choose not to upgrade, lol
                id_array = eval(result);
            }

            // select all the input fields for which we can provide help messages for
            var input_fields = $p.all("input[type=text], input[type=file], textarea, select");

            // check if the input field selected are not empty
            if (input_fields != null && input_fields.length > 0) {

                // iterate over all the input fields and show the help icon for those in the list
                for (var i = 0; i < input_fields.length; i++) {
                    var input_field = input_fields[i];

                    // iterate over all the field ids and add the id if equal to the current input id or name
                    for (var x = 0; x < id_array.fields.length; x++) {
                        var id = id_array.fields[x].field_id;

                        if (id == input_field.id || id == input_field.name) {
                            var span = document.createElement("span");
                            span.id = id;
                            span.style.paddingLeft = "10px";
                            span.style.display = "inline-block";
                            span.innerHTML = "<a href=\"#\" onclick=\"return false;\"><img src=\"images/icons/help_16.png\" alt=\"help\" width=\"17\" height=\"17\" border=\"0\" align=\"absmiddle\" /></a>";
                            span.onclick = function(e) {
                                if (!e)
                                    e = window.event;

                                var hd = $p.$("#help-dialog");
                                hd.style.position = "absolute";
                                hd.style.top = (e.clientY + system.getScrollXY()[1] + 10) + "px";
                                hd.style.left = e.clientX + "px";
                                hd.style.zIndex = "1000";
                                hd.focus();

                                // get the id used
                                var sp_id = this.id;

                                // show the help-dialog and load the help content 
                                $p('#help-dialog').show(function() {
                                    // hide any applets or floatable objects that on the page obstruct the div
                                    var applets = $p.all("applet");
                                    for (var i = 0; i < applets.length; i++) {
                                        applets[i].style.visibility = 'hidden';
                                    }

                                    var query = "action=load_help&field=" + sp_id;
                                    $p.post(system.ajax_page, query, function(data) {
                                        $p('#popup-content').html(data);
                                    });
                                });
                            };

                            var f = input_fields[i];

                            f.parentNode.appendChild(span);
                        }
                    }
                }
            }
        });
    },
    createPageLinkers: function() {
        $p.all("input[type=text].page-linker", function(el) {

            var span = document.createElement("span");
            span.setAttribute('data-field-id', el.id);
            span.style.paddingLeft = "5px";
            span.style.display = "inline-block";
            span.innerHTML = "<a href=\"#\" title='Select Page To Link To' onclick=\"return false;\"><img src=\"images/icons/folder_link.png\" alt=\"help\" width=\"17\" height=\"17\" border=\"0\" align=\"absmiddle\" /></a>";
            span.onclick = function(e) {
                system.selectSiteLink(e, document.getElementById(this.getAttribute('data-field-id')));
            };

            el.parentNode.appendChild(span);
        });
    },
    /**
     * Show a popup to enable a user select a link to a part of the site.
     *
     * @param e event object
     * @param field the target field to which the selected link will go to
     */
    selectSiteLink: function(e, field) {

        if (!e)
            e = window.event;

        var hd = $p("#help-dialog").node();
        hd.style.position = "absolute";
        hd.style.top = (e.clientY + system.getScrollXY()[1] + 10) + "px";
        hd.style.left = e.clientX + "px";
        hd.style.zIndex = "1000";

        $p('#help-dialog').show(function() {
            // if the page is cache exists, the cancel the ajax request
            if (system.page_list_cache != null) {
                return;
            }

            // build the query request for the list of possible pages to link to
            var query = 'action=load_site_links';
            $p.post(system.ajax_page, query, function(data) {

                $p("#popup-content").html(data);

                // cache the returned data of the call will not be done again for as long
                // as the cache exists
                system.page_list_cache = data;

                // attach the folder handlers
                system.attachFolderHandlers(".cms-tree");

                // attach the handlers for the links in the tree
                $p('#popup-content a').bind('click', function(e) {
                    field.value = $p(this).attr('data-href');
                    system.hidePopup();
                    return false;
                });
            });
        });
    },
    attachFolderHandlers: function(el_id) {
        var dirTree = $p(el_id).node();

        if (!dirTree) {
            return;
        }

        var liNodes = dirTree.getElementsByTagName("li");

        for (var i = 0; i < liNodes.length; i++) {
            var node = liNodes.item(i);

            if (node.className == "dir_name") {
                node.onclick = function(e) {
                    if (!e)
                        var e = window.event;

                    var uls = this.getElementsByTagName("ul");

                    for (var x = 0; x < uls.length; x++) {
                        var ul = uls.item(x);
                        if (ul.parentNode == this) { // only expand direct childNodes
                            if (ul.style.display == "block") {
                                ul.style.display = "none";
                            } else {
                                ul.style.display = "block";
                            }
                        }
                    }

                    system.stopEvent(e);
                }
            }

            if (node.className == "file_name") {
                // prevent unnecesarry expansion of tree nodes
                node.onclick = function(e) {
                    system.stopEvent(e);
                }
            }
        }
    },
    stopEvent: function(e) {
        if (!e)
            e = window.event;

        //e.cancelBubble is supported by IE - this will kill the bubbling process.
        e.cancelBubble = true;
        //e.returnValue = false;

        //e.stopPropagation works only in Firefox.
        if (e.stopPropagation) {
            e.stopPropagation();
            //e.preventDefault();
        }
        return false;
    }
};


$(document).ready(function() {
    system.init();
});
